import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/HomeView.vue";
import user from "./modules/user";
Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    redirect: "/index", // 重定向:重新指向其它path,会改变网址: "/index",
    children: user,
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../views/AboutView.vue"),
  },
  // 登录页面路由
  {
    path: "/Login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  // tab栏地址
  {
    path: "/newTabs",
    name: "newTabs",
    component: () => import("../views/management/newTabs.vue"),
  },
  // 搜索栏地址
  {
    path: "/switch",
    name: "switch",
    component: () => import("../views/management/switch.vue"),
  },
  // 404页面
  {
    path: "/err",
    name: "err",
    component: () => import("../views/page/err.vue"),
  },
  // 404页面
  {
    path: "/detail",
    name: "detail",
    component: () => import("../views/management/detail.vue"),
  },
  // 优惠券组件路由
  {
    path: "/coupon",
    name: "coupon",
    component: () => import("../components/coupon.vue"),
    meta: {
      isTop: true,
    },
  },
  // 客服路由
  {
    path: "/service",
    name: "service",
    component: () => import("../views/management/service.vue"),
    meta: {
      isTop: true,
    },
  },
  // 地址路由
  {
    path: "/site",
    name: "site",
    component: () => import("../views/management/site.vue"),
  },
  // 结算路由
  {
    path: "/close",
    name: "close",
    component: () => import("../views/management/close.vue"),
  },
];

const router = new VueRouter({
  routes,
});
// 动态路由
user.forEach((res) => {
  routes[0].children.push({
    path: res.path,
    name: res.name,
    component: res.component,
  });
});
// 路由拦截
router.beforeEach((to, form, next) => {
  if (to.matched.length == 0) {
    // 跳转到404页面
    next("/err");
  } else {
    if (
      to.matched.some((v) => {
        return v.meta.isTop == true;
      })
    ) {
      // 判断是否有token值
      if (localStorage.getItem("token")) {
        next();
      } else {
        // 没有token值就返回登录页面
        next("/login");
      }
    } else {
      next();
    }
  }
});
export default router;
